#pragma once
#include <iostream>
#include "include/mysql.h"
#include <string>
#include <jsoncpp/json/json.h>
#include "log.hpp"

using namespace std;

class Mysql_Util
{
public:
    static MYSQL* mysql_create(const std::string host, const std::string user, 
        const std::string passwd, const std::string db, int port)
    {
        MYSQL* mysql = mysql_init(NULL);
        if(mysql == NULL)
        {
            LOG(ERROR) << "创建mysql句柄失败" << "\n";
            return NULL;
        }
        if(NULL == mysql_real_connect(mysql, host.c_str(), user.c_str(), 
        passwd.c_str(), db.c_str(), port, NULL, 0))
        {
            LOG(ERROR) << "连接数据库失败" << "\n";
            std::cerr << mysql_error(mysql) << std::endl;
            mysql_close(mysql);
            return NULL;
        }
        mysql_set_character_set(mysql, "utf8");
        return mysql;                             
    }
    static bool mysql_exe(MYSQL* mysql, const std::string& sql)
    {
        if(0 != mysql_query(mysql, sql.c_str()))
        {
            LOG(ERROR) << "执行sql语句失败" << "\n";
            std::cerr << mysql_error(mysql) << std::endl;
            return false;
        }
        return true;
    }
    static void mysql_des(MYSQL* mysql)
    {
        if(mysql != NULL)
        {
            mysql_close(mysql);
        }
    }
};

class Json_util
{
public:
    // 序列化
    static void serializa(const Json::Value &root, string& str)
    {
        Json::StyledWriter writer;
        str = writer.write(root);
    }
    // 反序列化
    static void unserializa(const string& str, Json::Value &root)
    {
        Json::Reader reader;
        reader.parse(str, root);
    }
};

